package com.ztf.shopping.web.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ztf.shopping.bean.User;
import com.ztf.shopping.service.UserService;
import com.ztf.shopping.service.imp.UserServiceImp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/SubmitPwd")
public class SubmitPwd extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String oldPwd = request.getParameter("oldPwd");
        String newPwd = request.getParameter("newPwd");
        String code = request.getParameter("code");
        String vifCode = (String) request.getSession().getAttribute("vifCode");
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        ObjectMapper om = new ObjectMapper();
        Map<String,String> map = new HashMap<>();
        if (!vifCode.equals(code)){
            //验证码不正确
            map.put("msg","验证码不正确");
            om.writeValue(response.getOutputStream(),map);
            return;
        }

        if (!loginUser.getPwd().equals(oldPwd)){
            //旧密码不正确
            map.put("msg","旧密码不正确");
            om.writeValue(response.getOutputStream(),map);
            return;
        }

        if (loginUser.getPwd().equals(newPwd)){
            //旧密码不能与新密码相同
            map.put("msg","旧密码不能与新密码相同");
            om.writeValue(response.getOutputStream(),map);
            return;
        }

        //修改用户个人密码
        UserService userService = new UserServiceImp();
        loginUser.setPwd(newPwd);
        userService.changeUser(loginUser);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
